package com.jn.rxjava.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;
import com.jn.rxjava.R;
import com.jn.rxjava.entity.BingResponse.BingImage;
import com.jn.rxjava.views.ImageDialogFragment;

import java.util.List;

public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {

    private List<BingImage> images;
    private FragmentActivity activity;

    public ImageAdapter(FragmentActivity activity) {
        this.activity = activity;
    }

    public void setImages(List<BingImage> images) {
        this.images = images;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image, parent, false);
        return new ImageViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ImageViewHolder holder, int position) {
        BingImage image = images.get(position);
        holder.title.setText(image.getTitle());

        holder.itemView.setOnClickListener(v -> {
            // 显示小窗口
            ImageDialogFragment.newInstance(image).show(activity.getSupportFragmentManager(), "image_dialog");
        });
    }

    @Override
    public int getItemCount() {
        return images != null ? images.size() : 0;
    }

    static class ImageViewHolder extends RecyclerView.ViewHolder {
        TextView title;

        ImageViewHolder(View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.title);
        }
    }
}